<script setup lang="ts">
import type { User } from '@/apis/acl/user/type'
import { addUserService, updateUserService } from '@/apis/acl/user'
import { ref } from 'vue'
const drawerVisible = ref<boolean>(false)
// 绑定form表单
const formRef = ref()
// 收集用户信息
const userInfo = ref<User>({
  name: '',
  username: '',
  password: ''
})
// rules
const rules = {
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { pattern: /^\w{5,15}$/, message: '用户名必须是5-15位', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value.length < 6) {
          callback(new Error('昵称不能少于6位'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码不能少于6位,不多于15位', trigger: 'blur' }
  ]
}
// 添加角色
const openUserDrawer = (row: User) => {
  drawerVisible.value = true
  Object.assign(userInfo.value, row)
  // userInfo.value = { ...row }
}
const model = defineModel()

// 确定
const onConfirm = async () => {
  model.value = ''
  await formRef.value.validate()
  if (userInfo.value.id) {
    await updateUserService(userInfo.value)
    model.value = 'update'
  } else {
    await addUserService(userInfo.value)
    model.value = 'add'
  }
  await ElNotification({
    type: 'success',
    title: '温馨提示',
    message: userInfo.value.id ? '修改成功' : '添加成功'
  })
  drawerVisible.value = false
}

// 关闭drawer
const drawerClosed = () => {
  formRef.value.clearValidate()
}

defineExpose({
  openUserDrawer
})
</script>

<template>
  <!-- drawer抽屉 -->
  <el-drawer
    v-model="drawerVisible"
    @closed="drawerClosed"
    :title="userInfo.id ? '修改用户' : '添加用户'"
  >
    <template #default>
      <el-form :model="userInfo" :rules="rules" ref="formRef" status-icon>
        <el-form-item label="用户姓名" prop="name">
          <el-input
            placeholder="请你输入用户姓名"
            v-model="userInfo.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="username">
          <el-input
            v-model="userInfo.username"
            placeholder="请你输入用户昵称"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!userInfo.id">
          <el-input
            placeholder="请你输入用户密码"
            v-model="userInfo.password"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button type="primary" @click="onConfirm">确定</el-button>
    </template>
  </el-drawer>
</template>
